import { useNoticeStore } from '@/store'

export default class SettlementBillHandler {
    sqlite: any
    constructor(sqlite: any) {
        this.sqlite = sqlite
    }

    /**
     * 获取信息
     */
    getHistoryList(userId: any, firstTime: any) {
        return new Promise((resolve, reject) => {
            // 直接查询本地历史信息
            this.sqlite.imSettlementBill
                .historyList(userId, firstTime)
                .then((list: any) => {
                    if (list.length == 0) {
                        // 查询服务器
                        uni.$u.$api.ImSettlementBill.historyList(firstTime)
                            .then((res: any) => {
                                resolve(res)
                            })
                            .catch((e: any) => {
                                console.error(e)
                                reject([])
                            })
                    } else {
                        resolve(list)
                    }
                })
                .catch((e: any) => {
                    reject([])
                    console.error('sqlite.imSettlementBill', e)
                })
        })
    }

    /**
     * 处理未读通知
     */
    dealUnread(userId: string | number) {
        // 查询未读id列表
        this.sqlite.imSettlementBill.getUnreadIdList(userId).then((idList: any) => {
            // console.log('idList', idList)
            if (idList) {
                // 调用api阅读接口，无需等待
                uni.$u.$api.ImSettlementBill.read(idList)
                // 更新本地阅读状态, 全部更新为3
                let data = idList.map((it: any) => {
                    return {
                        id: it,
                        isRead: 3
                    }
                })
                this.sqlite.imSettlementBill.updateById(data)
                // 清空未读数
                const noticeStore = useNoticeStore()
                noticeStore.clearSettlementBillUnread()
                // 重置总未读记录数
                uni.$u.$imHandler.updateTabBarText()
            }
        })
    }

    /**
     * 处理未读通知
     */
    dealUnreadByNewSettlementBill(settlementBill: any) {
        // 本地添加/更新消息
        return new Promise(resolve => {
            settlementBill.isRead = 3
            this.sqlite.imSettlementBill.saveOrUpdateAfterSales([settlementBill])
            // 调用api阅读接口，无需等待
            uni.$u.$api.ImSettlementBill.read([settlementBill.id])
            resolve(settlementBill)
        })
    }
}
